#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QVBoxLayout>
#include <QKeyEvent>
#include <QDebug>
#include <QEvent>
#include <QEvent>
#include <QKeyEvent>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    // , ui(new Ui::MainWindow)
{
    // ui->setupUi(this);

    // 初始化UI组件
    lineEdit = new QLineEdit(this);
    listView = new QListView(this);
    model = new QStringListModel(this);

    // 设置模型
    listView->setModel(model);

    // 初始数据
    initialItems = QStringList() <<"apple" << "banana"<< "cherry"<< "date"<< "elderberry"<< "a pple";
    model->setStringList(initialItems);

    // 布局
    QVBoxLayout *layout = new QVBoxLayout;
    layout->addWidget(lineEdit);
    layout->addWidget(listView);

    QWidget *centralWidget = new QWidget(this);
    centralWidget->setLayout(layout);
    setCentralWidget(centralWidget);

    // lineEdit->installEventFilter(this);
    // 连接信号和槽
    connect(lineEdit, &QLineEdit::textChanged, this, &MainWindow::onTextChanged);
}

MainWindow::~MainWindow()
{
    // delete ui;
}

void MainWindow::onTextChanged(const QString &text)
{
    // if (text.isEmpty() || !text.endsWith(' '))
    if (text.isEmpty())
        return;

    QString keyword = text;//.trimmed();
    if (keyword.isEmpty())
        return;

    // 过滤数据
    QStringList filteredItems;
    for (const QString &item : initialItems) {
        if (item.contains(keyword, Qt::CaseInsensitive)) {
            filteredItems << item;
        }
    }

    // 更新模型
    model->setStringList(filteredItems);

    // 处理过滤结果
    if (filteredItems.size() == 1) {
        qDebug() << "唯一一条记录: " << filteredItems.first();
    }
}

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Space) {
        // lineEdit->setText(lineEdit->text() + " ");
        qDebug() << "按空格按空格按空格:"<<lineEdit->text();
    }
    QMainWindow::keyPressEvent(event);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event) {
    if(watched ==  lineEdit){
        if(event->type() == QEvent::KeyPress){
            QKeyEvent *keyEvent = static_cast<QKeyEvent*> (event);
            if(keyEvent->key() == Qt::Key_Space){
                qDebug() << "============>:"<<lineEdit->text();
            }
            return true;
        }else{
            qDebug() << "怡然有余乐，于何劳智慧？"<<lineEdit->text();
        }
    }
    return QMainWindow::eventFilter(watched, event);
}

